from distutils.errors import DistutilsError
import os
import sys

from setuptools import Command


class BaseMigrationCommand(Command):

    user_options = [
                    ('package=', 'p', "the package containing the migration scripts"),
#                    ('verbose', 'v', "produce verbose output"),
                    ]
#    boolean_options = ['verbose']

    def initialize_options(self):
        self.package = None
        self.package_dir = None
        self.verbose = self.distribution.verbose

    def finalize_options(self):
        self.assert_package_defined()
        self.set_package_directory()
        self.assert_package_dir_defined()

    def assert_package_defined(self):
        if self.package is None:
            raise DistutilsError("You must defined a package")

    def set_package_directory(self):
        self.package_dir = self.package_path()

    def package_path(self):
        package_dir_map = self.distribution.package_dir
        if package_dir_map is None:
            return self.imported_package_path()
        elif self.package in package_dir_map:
            return os.path.abspath(package_dir_map.get(self.package))
        elif '' in package_dir_map:
            return os.path.abspath(package_dir_map.get(''))
        else:
            return self.imported_package_path()

    def imported_package_path(self):
        try:
            first_package_dir = os.path.dirname(__import__(self.package).__file__)
            package_portion = self.package.split('.')[0]
            return first_package_dir[:-len(package_portion)]
        except ImportError:
            return os.path.abspath(os.getcwd())

    def assert_package_dir_defined(self):
        if self.package_dir is None:
            raise DistutilsError("The package directory is not defined")

